package com.amigo.online.consumer.user.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amigo.online.consumer.user.common.ConstantValue;

/**
 * fastDsf 连接池
 * 
 * @author Administrator
 *
 */
public class ConnectionPool {

	private static final Logger logger = LoggerFactory.getLogger(ConnectionPool.class);

	// 最大连接数,可以写配置文件
	private int size = 64;

	private int initSize = 20;
	// 被使用的连接
	private ConcurrentHashMap<StorageClient1, Object> busyConnectionPool = null;

	// 空闲的连接
	private ArrayBlockingQueue<StorageClient1> idleConnectionPool = null;

	private Object obj = new Object();

	// 单例
	private ConnectionPool() {
		logger.info("--------------单例初始化------------");
		busyConnectionPool = new ConcurrentHashMap<StorageClient1, Object>();
		idleConnectionPool = new ArrayBlockingQueue<StorageClient1>(size);
		init(initSize);
	}

	private static class SingletonInstance {
		private static final ConnectionPool instance = new ConnectionPool();
	}

	public static ConnectionPool getInstance() {
		return SingletonInstance.instance;
	}

	public void showRestConnetion() {
		logger.info("被使用的连接数:{},空闲的连接数:{}", busyConnectionPool.size(), idleConnectionPool.size());
	}

	// 取出连接
	public StorageClient1 checkout(int waitTime) {
		StorageClient1 storageClient1 = null;
		try {
			storageClient1 = idleConnectionPool.poll(waitTime, TimeUnit.SECONDS);
			logger.info(storageClient1.toString());
			if (storageClient1 != null) {
				busyConnectionPool.put(storageClient1, obj);
			}
			//logger.info("FASTDSF连接池,已经使用连接数:" + busyConnectionPool.size() + " 剩余可用连接数:" + idleConnectionPool.size());
		} catch (InterruptedException e) {
			storageClient1 = null;
			logger.error("Get Connection Failed!");
		}
		return storageClient1;
	}

	public StorageClient1 CheckoutConcurrent() {
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = null;
		try {
			trackerServer = trackerClient.getConnection();
		} catch (IOException e) {
			logger.error("Get Connection Failed!");
		}
		StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
		return storageClient1;
	}

	// 回收连接
	public void checkin(StorageClient1 storageClient1) {
		if (busyConnectionPool.remove(storageClient1) != null) {
			idleConnectionPool.add(storageClient1);
			//logger.info("FASTDSF连接池,已经使用连接数:{}!剩余可用连接数:{}", busyConnectionPool.size(), idleConnectionPool.size());
		}
	}

	public void checkinConcurrent(StorageClient1 storageClient1) {
		idleConnectionPool.remove();
		idleConnectionPool.add(storageClient1);
	}

	// 如果连接无效则抛弃，新建连接来补充到池里
	public void drop(StorageClient1 storageClient1) {
		if (busyConnectionPool.remove(storageClient1) != null) {
			TrackerServer trackerServer = null;
			try {
				trackerServer = new TrackerClient().getConnection();
				StorageClient1 newStorageClient1 = new StorageClient1(trackerServer, null);
				idleConnectionPool.add(newStorageClient1);
				//logger.info("FASTDSF连接池,已经使用连接数:{}!剩余可用连接数:{}", busyConnectionPool.size(), idleConnectionPool.size());
			} catch (IOException e) {
				logger.error("Get Connection Failed!");
			} finally {
				if (trackerServer != null) {
					try {
						trackerServer.close();
					} catch (IOException e) {
						logger.error("Get Connection Failed!");
					}
				}
			}
		}
	}

	// 初始化连接池
	private void init(int size) {
		initClientGlobal();
		TrackerServer trackerServer = null;
		try {
			TrackerClient trackerClient = new TrackerClient();
			// 只需要一个tracker server连接
			trackerServer = trackerClient.getConnection();
			StorageServer storageServer = null;
			StorageClient1 storageClient1 = null;
			for (int i = 0; i < size; i++) {
				storageClient1 = new StorageClient1(trackerServer, storageServer);
				idleConnectionPool.add(storageClient1);
				logger.info("------------------------- :connection +1");
			}

		} catch (IOException e) {
			logger.error("Get Connection Failed!");
		} finally {
			if (trackerServer != null) {
				try {
					trackerServer.close();
				} catch (IOException e) {
					logger.error("Get Connection Failed!");
				}
			}
		}
	}

	// 初始化客户端
	private void initClientGlobal() {

		// 连接超时时间
		ClientGlobal.setG_connect_timeout(30000);
		// 网络超时时间
		ClientGlobal.setG_network_timeout(60000);

		ClientGlobal.setG_anti_steal_token(false);
		// 字符集
		ClientGlobal.setG_charset("UTF-8");

		ClientGlobal.setG_secret_key("FastDFS1234567890");

		// HTTP访问服务的端口号
		ClientGlobal.setG_tracker_http_port(80);

		InetSocketAddress[] trackerServers = new InetSocketAddress[1];

		trackerServers[0] = new InetSocketAddress(ConstantValue.FASTDSF_PORT, 22122);
		// trackerServers[1] = new InetSocketAddress("179.127.4.142", 22122);
		TrackerGroup trackerGroup = new TrackerGroup(trackerServers);
		// tracker server 集群
		ClientGlobal.setG_tracker_group(trackerGroup);
	}

}